package com.zhixiang.core.util;


import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.ServletContext;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.context.SecurityContextHolder;

import com.zhixiang.core.web.filter.SecurityInterceptorFilter;
import com.zhixiang.xaec.entity.system.AppFunction;
import com.zhixiang.xaec.entity.system.AppUser;
import com.zhixiang.xaec.entity.system.FunUrl;
import com.zhixiang.xaec.service.system.AppFunctionService;
import com.zhixiang.xaec.service.system.FunUrlService;

@SuppressWarnings({"rawtypes","unchecked","unused"})
public class AppUtil implements ApplicationContextAware
{
    private static Log logger = LogFactory.getLog(AppUtil.class);

    private static Map configMap = new HashMap();

    private static ServletContext servletContext = null;

    private static Map onlineUsers = new LinkedHashMap();

    private static ApplicationContext appContext;

    private static Map orgMenus = null;

    private static Map itemsMenus = null;

    private static Map allTopModels = null;

    private static Document menuDocument = null;

    public static Map publicTopModules = null;

    private static Set publicMenuIds = null;

    public void setApplicationContext(ApplicationContext applicationcontext)
        throws BeansException
    {
//        AppUtil _tmp = this;
        appContext = applicationcontext;
    }

    public static Map getOrgMenus()
    {
        return orgMenus;
    }

    public static Map getItemsMenus()
    {
        return itemsMenus;
    }

    public static Map getAllTopModels()
    {
        return allTopModels;
    }

    public static Document getMenuDocument()
    {
        return menuDocument;
    }

    public static void setPublicMenuIds(Set set)
    {
        publicMenuIds = set;
    }

    public static Map getPublicTopModules()
    {
        return publicTopModules;
    }

    public static void setPublicTopModules(Map map)
    {
        publicTopModules = map;
    }

    public static Object getBean(String s)
    {
        return appContext.getBean(s);
    }

    public static Map getOnlineUsers()
    {
        return onlineUsers;
    }

    public static void removeOnlineUser(String s)
    {
        onlineUsers.remove(s);
    }

    /*
     * public static void addOnlineUser(String s, AppUser appuser) { if
     * (!onlineUsers.containsKey(s)) { OnlineUser onlineuser = new OnlineUser();
     * onlineuser.setFullname(appuser.getFullname()); onlineuser.setSessionId(s);
     * onlineuser.setUsername(appuser.getUsername()); onlineuser.setUserId(appuser.getUserId()); if
     * (!appuser.getUserId().equals(AppUser.SUPER_USER)) onlineuser.setDepPath("." +
     * appuser.getDepartment().getPath()); Set set = appuser.getRoles(); StringBuffer stringbuffer
     * = new StringBuffer(","); for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
     * AppRole approle = (AppRole)iterator.next(); stringbuffer .append(approle.getRoleId() + ",");
     * } onlineuser.setRoleIds(stringbuffer.toString()); onlineuser.setTitle(appuser.getTitle());
     * onlineUsers.put(s, onlineuser); } }
     */

    public static String getAppAbsolutePath()
    {
        return servletContext.getRealPath("/");
    }

    public static String getMenuAbDir()
    {
        return getAppAbsolutePath() + "/resources/js/menu/xml/";
    }

    public static String getMenuXslDir()
    {
        return getAppAbsolutePath() + "/resources/js/menu/";
    }

    public static String getFlowFormAbsolutePath()
    {
        String s = (String)configMap.get("app.flowFormPath");
        if (s == null) s = "/WEB-INF/FlowForm/";
        return getAppAbsolutePath() + s;
    }

    public static String getMobileFlowFlowAbsPath()
    {
        return getAppAbsolutePath() + "/mobile/flow/FlowForm/";
    }

    public static void reloadSecurityDataSource()
    {
        SecurityInterceptorFilter securityinterceptorfilter = (SecurityInterceptorFilter)getBean("securityInterceptorFilter");
        securityinterceptorfilter.loadDataSource();
    }

    /*
     * public static String getLicCode() { return SystemTool.getSysMacInfo() ; }
     */

    /*
     * public static void licCheck() { Timer timer = new Timer(); timer.schedule(new TimerTask() {
     * public void run() { Boolean is_true = AppUtil.getStart(); if (!is_true.booleanValue()) {
     * logger.error("未检查到授权或授权已经过期...."); logger.error("服务停止，请尽快购买授权...."); System.exit(0); } else
     * { logger.info("检查授权成功...."); } } } , 30000L); }
     */

    /*
     * public static Boolean getStart() { String s = "/WEB-INF/classes/conf/"; String s1 =
     * getAppAbsolutePath() + s + "/license.lic"; Properties properties = new Properties(); Boolean
     * istrue = Boolean.valueOf(false); try { FileInputStream fileinputstream = new
     * FileInputStream(s1); InputStreamReader inputstreamreader = new
     * InputStreamReader(fileinputstream, "UTF-8"); properties.load(inputstreamreader); String lic
     * =properties.getProperty("start") DESPlus des = new DESPlus(DateGather.getDateTime12());
     * istrue = SystemTool.chkLicense2(des.decrypt(lic)); Boolean istrue = Boolean.valueOf(false);
     * try { FileInputStream fileinputstream = new FileInputStream(s1); byte [] b = new
     * byte[fileinputstream.available()]; fileinputstream.read(b); String lic = byte2hex(b);
     * BufferedReader in = new BufferedReader(new InputStreamReader(fileinputstream)); StringBuffer
     * buffer = new StringBuffer(); String line = ""; while ((line = in.readLine()) != null){
     * buffer.append(line).append("\r\n"); } String lic =buffer.toString(); istrue =
     * SystemTool.chkLicense3(lic); } catch (Exception exception) {
     * logger.error(exception.getMessage()); exception.getStackTrace(); } return istrue; }
     */

    public static void init(ServletContext servletcontext)
    {
        servletContext = servletcontext;
        String s = servletContext.getRealPath("/WEB-INF/classes/conf/");
        String s1 = s + "/config.properties";
//        String intall = s + "/install.ini";

        Properties properties = new Properties();
//        Properties properties2 = new Properties();
        try
        {
            FileInputStream fileinputstream = new FileInputStream(s1);
            InputStreamReader inputstreamreader = new InputStreamReader(fileinputstream, "UTF-8");
            properties.load(inputstreamreader);

            Iterator iterator = properties.keySet().iterator();
            String s2;
            for (; iterator.hasNext(); configMap.put(s2, properties.get(s2)))
                s2 = (String)iterator.next();
        }
        catch (Exception exception)
        {
            logger.error(exception.getMessage());
            exception.getStackTrace();
        }
        // reloadSysConfig();
        // CompanyService companyservice = (CompanyService)getBean("companyService");
        // List list = companyservice.findCompany();
        // if (list.size() > 0) {
        // Company company = (Company)list.get(0);
        // configMap.put("app.logoPath", company.getLogo());
        // configMap.put("app.companyName", company.getCompanyName());
        // }
        reloadMenu();
        logger.info("=============恭喜！xaecSafe启动成功=============");
    }

    public static void reloadMenu()
    {
        orgMenus = MenuUtil.getAllOrgMenus();
        itemsMenus = MenuUtil.getAllItemsMenus(orgMenus);
        menuDocument = MenuUtil.mergeOneDoc(orgMenus);
        allTopModels = MenuUtil.getTopModules(menuDocument);
        publicTopModules = MenuUtil.getPublicTopModules(allTopModels);
    }

    public static void synMenu()
    {
        AppFunctionService appfunctionservice = (AppFunctionService)getBean("appFunctionServiceImpl");
        FunUrlService funurlservice = (FunUrlService)getBean("funUrlServiceImpl");
        Iterator iterator = orgMenus.keySet().iterator();
        while (iterator.hasNext())
        {
            Document document = (Document)orgMenus.get(iterator.next());
            List list = document.getRootElement().selectNodes("/Menus/Items//Item/Function");
            int i = 0;
            while (i < list.size())
            {
                Element element = (Element)list.get(i);
                String s = element.attributeValue("id");
                String s1 = element.attributeValue("text");
                AppFunction appfunction = appfunctionservice.getByKey(s);
                if (appfunction == null)
                    appfunction = new AppFunction(s, s1);
                else
                    appfunction.setFunName(s1);
                List list1 = element.selectNodes("./url");
                appfunctionservice.save(appfunction);
                for (int j = 0; j < list1.size(); j++ )
                {
                    Node node = (Node)list1.get(j);
                    String s2 = node.getText();
                    FunUrl funurl = funurlservice.getByPathFunId(s2, appfunction.getFunctionId());
                    if (funurl == null)
                    {
                        FunUrl funurl1 = new FunUrl();
                        funurl1.setUrlPath(s2);
                        funurl1.setAppFunction(appfunction);
                        funurlservice.save(funurl1);
                    }
                }

                i++ ;
            }
        }
    }

    public static Document getGrantMenuDocument()
    {
        String s = servletContext.getRealPath("/resources/js/menu") + "/menu-grant.xsl";
        Document document = null;
        try
        {
            document = XmlUtil.styleDocument(menuDocument, s);
        }
        catch (Exception exception)
        {
            logger.error("menu-grant.xsl transform has error:" + exception.getMessage());
        }
        return document;
    }

    public static boolean getIsSynMenu()
    {
        String s = (String)configMap.get("isSynMenu");
        return "true".equals(s);
    }

    public static Map getSysConfig()
    {
        return configMap;
    }

    /*
     * public static void reloadSysConfig() { SysConfigService sysconfigservice =
     * (SysConfigService)getBean("sysConfigService"); List list = sysconfigservice.getAll(); for
     * (Iterator iterator = list.iterator(); iterator.hasNext(); ) { SysConfig sysconfig =
     * (SysConfig)iterator.next(); configMap.put(sysconfig.getConfigKey(),
     * sysconfig.getDataValue()); } }
     */

    public static String getCompanyLogoPng()
    {
        String s = "/resources/images/ht-logo.png";
        // String s1 = (String)configMap.get("app.logoPath");
        // if (StringUtils.isNotEmpty(s1)) {
        // s = "/resources/attachFiles/" + s1;
        // }
        return s;
    }

    public static String getCompanyLogoGif()
    {
        String s = "/resources/images/ptms-logo.png";
        // String s1 = (String)configMap.get("app.logoPath");
        // if (StringUtils.isNotEmpty(s1)) {
        // s = "/resources/attachFiles/" + s1;
        // }
        return s;
    }

    public static String getCompanyName()
    {
        String s = "智翔软件科技控股有限公司";
        String s1 = (String)configMap.get("app.companyName");
        if (StringUtils.isNotEmpty(s1)) s = s1;
        return s;
    }

    public static boolean getSmsPort()
    {
        String s = (String)configMap.get("smsPort");
        return "true".equals(s);
    }

    public static boolean isSetupMode()
    {
        String s = (String)configMap.get("setupMode");
        return "true".equals(s);
    }
    
    public static String getUserName(){
        if(SecurityContextHolder.getContext() == null){  
            return null;  
        }  
          
        if(SecurityContextHolder.getContext().getAuthentication() == null){  
            return null;  
        }  
          
        AppUser userDetails = (AppUser) SecurityContextHolder  
                .getContext().getAuthentication().getPrincipal();  
          
        if(userDetails == null){  
            return null;  
        }  
        
        String userName = userDetails.getStaff().getName();  
        
        if(userName == null || userName.equals("")){  
            return null;  
        } 
        
        return userName;
        
    }
    
    /**
     * byte转哈希
     * 
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b)
    {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++ )
        {
            stmp = Integer.toHexString(b[n] & 0xFF);
            if (stmp.length() == 1)
                hs += ("0" + stmp);
            else
                hs += stmp;
        }
        return hs.toUpperCase();
    }

    /**
     * 哈希转byte
     * 
     * @param b
     * @return
     */
    public static byte[] hex2byte(byte[] b)
    {
        if ((b.length % 2) != 0) throw new IllegalArgumentException("长度不是偶数");

        byte[] b2 = new byte[b.length / 2];

        for (int n = 0; n < b.length; n += 2)
        {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte)Integer.parseInt(item, 16);
        }
        return b2;
    }
}
